<template>
  <el-card>
    <el-row :gutter="20">
      <el-col :span="13">
        <el-card>
          <!-- 刀组信息 -->
          <div class="tool_message">
            <div class="title_message">
              <div class="left">
                <div class="left_left">
                  <img src="../../assets/images/daozu.png" alt="" />
                  <span>刀组信息</span>
                </div>
                <div class="left_right">
                  <el-form :inline="true">
                    <el-form-item label="宽度搜索刀组:" style="margin-bottom: 0">
                      <el-select v-model="daozu" placeholder="宽度搜索刀组" size="mini" style="width: 110px">
                        <el-option label="全部" value=""> </el-option>
                        <el-option v-for="item in options" :key="item.pro_size" :label="item.pro_size"
                          :value="item.pro_size">
                        </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="切换算法:" style="margin-bottom: 0">
                      <el-select v-model="suanfa" placeholder="切换算法" size="mini" style="width: 110px">
                        <el-option v-for="item in options1" :key="item.id" :label="item.title" :value="item.id">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-form>
                </div>
              </div>
            </div>
            <div class="info">
              <p>
                <span>投入：{{ putInto }}</span><span>成材率：{{ yields }}%</span>
              </p>
            </div>
            <div class="tables">
              <el-table :data="tableData" border style="width: 100%; margin-top: 20px">
                <el-table-column prop="size_list" label="刀组" width="70%">
                </el-table-column>

                <el-table-column prop="weight_finish" label="重量（KG）" width="30%">
                  <template slot-scope="scope">
                    <div>
                      <el-input :value="scope.row.weight_finish"
                        @focus="changeWeight(scope.$index, scope.row)"></el-input>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="11">
        <el-card>
          <!-- 成品信息 -->
          <div class="tool_message">
            <div class="title_message">
              <div class="left">
                <div class="left_left">
                  <img src="../../assets/images/chengpin.png" alt="" />
                  <span>成品信息</span>
                </div>
              </div>
            </div>
            <div class="info">
              <p>
                <span>计划：{{ plan }}</span><span>下单：{{ placeOrder }}</span><span class="mini">单位：MM、KG</span>
              </p>
            </div>
            <div class="tables">
              <el-table :data="tableData1" border style="width: 100%; margin-top: 20px">
                <el-table-column prop="pro_size" label="规格">
                </el-table-column>

                <el-table-column prop="weight_limit" label="计划">
                </el-table-column>
                <el-table-column prop="weight_finish" label="下单">
                </el-table-column>
                <el-table-column prop="deviation" label="偏差">
                  <template slot-scope="scope">
                    {{ scope.row.deviation }}%
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <div class="btn">
            <el-button style="width: 100%" size="small" type="primary" block @click="handlerSubmit()">提交</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog title="重量调整" :visible.sync="dialogVisible" width="400px" :before-close="handleClose">
      <p><span>原卷规格：{{ sku }}</span><span style="color: #ff0000;margin-left:10px;">剩余：{{ sy }}KG</span></p>
      <p style="margin: 20px 0">
        <span>加工重量：</span><el-input-number :precision="2" :step="0.1" v-model="kg"></el-input-number>&nbsp;&nbsp;KG
      </p>
      <p>刀组信息：{{ weightObj.size_list }}</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitWeight()">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import { getCalculateApi, setCalculateApi, weightApi } from "@/api/index.js";
export default {
  data () {
    return {
      tableData: [],
      tableData1: [],
      retainData: [],
      options: [],
      options1: [
        {
          id: 1,
          title: "混合模式",
          level: "成材率优先",
        },
        {
          id: 2,
          title: "系统推荐",
          level: "成材率优先",
        },

        {
          id: 3,
          title: "成材率优先",
          level: "系统调优",
        },
        {
          id: 4,
          title: "系统调优",
          level: "刀组少优先",
        },
        {
          id: 5,
          title: "刀组少优先",
          level: "混合模式",
        },
      ],
      daozu: "",
      suanfa: 1,
      dialogVisible: false,
      sku: '',
      kg: 0,
      sy: 0,
      weightObj: {},
      currentIndex: 100000000000000,
      putInto: 0,
      yields: 0,
      currentInfo: {},
      computeType: "混合模式",
      plan: 0,
      placeOrder: 0,
      loading: false,
      changeDzWidth: false
    };
  },
  created () {
    this.loading = this.$loading({
      lock: true,
      text: '数据计算中，请稍等...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    this.getcCalculateList();
  },
  methods: {
    async getcCalculateList () {
      this.changeDzWidth = false
      let params = {
        company_id: this.$store.state.sizeMeet.company_id,
        no: this.$store.state.sizeMeet.auto_id,
        companyConfig: JSON.stringify(this.$store.state.companyConfig),
        computeType: this.computeType,
      };

      // let res = await ;
      let res = await setCalculateApi(params);

      if (res.code == 200) {
        this.currentInfo = res.data;
        this.$store.commit('SET_ORDERINFO', res.data)
        getCalculateApi(res.data).then((res) => {
          this.tableData = res.data.sizeMeet;
          this.tableData1 = res.data.products;
          this.options = res.data.products;
          this.$store.commit("SET_YJDATA", {});
          this.$store.commit("SET_CPDATA", {});
          this.retainData = JSON.parse(JSON.stringify(this.tableData))
          this.loading.close()
        });
      }
    },
    //改变重量
    changeWeight (index, row) {
      let size = row.m_size.split('*')
      if (size.length == 3) {
        this.sku = size[0] + '*' + size[1] + '*C'
        this.sy = size[2] && size[2] != 'C' ? Number(size[2] - row.weight_finish) : '--'
      } else {
        this.sku = row.m_size
      }

      this.currentIndex = index;
      this.kg = row.weight_finish
      this.dialogVisible = true;
      this.weightObj = this.tableData[index];
    },
    submitWeight () {
      let currentData = JSON.parse(
        JSON.stringify(this.tableData[this.currentIndex])
      );
      this.$set(this.tableData[this.currentIndex], "weight_finish", this.kg);

      let params = {
        company_id: this.currentInfo.company_id,
        no: this.currentInfo.no,
        materialSize: currentData.m_size,
        oldWeight: currentData.weight_finish,
        // changeWeight:
        sizeList: currentData.size_list,
        companyConfig: JSON.stringify(this.$store.state.companyConfig),
      };
      params.changeWeight = this.tableData[this.currentIndex].weight_finish;
      weightApi(params).then((res) => {
        if (res.code == 200) {
          this.tableData1 = res.data.products;
        }
      });

      this.currentIndex = 100000000000000;
      this.dialogVisible = false;
    },
    handleClose () {
      this.dialogVisible = false;
      this.currentIndex = 100000000000000;
    },
    //获取等于号后面的值 取消空字符串
    getValueAfterEqualSign (str) {
      // 使用正则表达式匹配等号后的内容
      const match = str.match(/=(.*)/);
      if (match && match.length > 1) {
        // 返回等号后的值，去除空白字符
        let content = match[1].trim().split("-");
        let difference = this.preciseSubtraction(content[0], content[1]);
        return (difference / content[0]).toFixed(5)
      }
      // 如果没有匹配到，返回null
      return null;
    },
    preciseSubtraction (num1, num2) {
      let decimal1, decimal2;
      let num1String = num1.toString();
      let num2String = num2.toString();

      // 检查是否有小数点
      if (num1String.includes(".")) {
        decimal1 = num1String.split(".")[1].length;
      } else {
        decimal1 = 0;
      }

      if (num2String.includes(".")) {
        decimal2 = num2String.split(".")[1].length;
      } else {
        decimal2 = 0;
      }

      // 对齐小数点后的位数
      let maxDecimal = Math.max(decimal1, decimal2);
      let multiplier = Math.pow(10, maxDecimal);

      let whole1 = num1 * multiplier;
      let whole2 = num2 * multiplier;

      let difference = whole1 - whole2;

      return difference / multiplier;
    },
    //提交
    handlerSubmit () {
      this.$router.push('/toolDetail')
    }
  },
  watch: {
    tableData: {
      handler (val) {
        if (!this.changeDzWidth) {
          let count = 0;
          let total = 0;
          val.map((item) => {
            if (item.weight_finish > 0) {
              total += item.weight_finish;
              count +=
                item.weight_finish * this.getValueAfterEqualSign(item.size_list);
            }
          });
          this.putInto = total;
          this.yields = (count / total * 100).toFixed(2);
          this.$store.commit('SET_ORDER_WEIGHT', total)
          this.$store.commit('SET_YIEID', this.yields)
        }

      },
      deep: true,
      immediate: true,
    },
    tableData1: {
      handler (val) {
        let planCount = 0;
        let placeOrderCount = 0;
        val.map((item) => {
          planCount += item.weight_limit;
          placeOrderCount += item.weight_finish;
        });
        this.plan = planCount;
        this.placeOrder = placeOrderCount;
      },
      immediate: true,
      deep: true,
    },
    daozu: {
      handler (val) {
        if (val) {
          this.changeDzWidth = true
          let needValue = val.split("*")
          if (needValue.length > 0) {
            this.tableData = this.retainData.filter(item => (needValue[0] && item.size_list.search(needValue[0]) != -1) || (needValue[1] && item.size_list.search(needValue[1]) != -1) || item.weight_finish != 0)
          }

        } else {
          this.getcCalculateList();
        }
      }
    },
    suanfa: {
      handler (val) {
        if (val) {
          let currentObj = this.options1.find((item) => item.id == val);
          this.computeType = currentObj.title;
          this.putInto = 0;
          this.yield = 0;
          this.getcCalculateList();
        }
      },
    },

  },
};
</script>

<style lang="scss" scoped>
div.tool_message {
  div.title_message {
    div.left {
      // display: flex;
      // align-items: center;
      // justify-content: space-between;

      div.left_left {
        display: flex;
        align-items: center;

        img {
          width: 16px;
          margin-right: 10px;
        }
      }

      div.left_right {
        display: flex;
        justify-content: flex-end;
      }
    }
  }

  div.info {
    width: 100%;
    border-bottom: 1px solid #ddd;
    padding: 10px;

    p {
      span+span {
        margin-left: 20px;
      }

      span.mini {
        font-size: 14px;
      }
    }
  }

  ::v-deep .el-table__header,
  ::v-deep .el-table__body {
    width: 100% !important;
  }

  ::v-deep .el-table__row {
    width: 100% !important;
  }
}

.btn {
  width: 300px;
  margin: 20px auto;
}

::v-deep .el-table__empty-block {
  width: 100% !important;
}
</style>
